<template>
  <div class="main-content pd16">

    <!--搜索栏-->
    <el-form class="search-form" ref="searchFormRef" :model="searchForm" :inline="true" label-width="70px">

      <el-form-item label="角色名称" prop="name" label-width="70px">
        <el-input v-model="searchForm.name" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="状态" prop="isDisable" label-width="40px">
        <el-select v-model="searchForm.isDisable" placeholder="请选择" clearable style="width: 100px">
          <el-option v-for="dict in enu_common_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="searchData">搜索</el-button>
        <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>

    </el-form>

    <!--按钮组-->
    <div class="fx mgb12">
      <el-button type="primary" plain size="small" icon="Plus" @click="openAdd">新增角色</el-button>
      <el-button type="danger" plain size="small" icon="Delete" @click="deleteBatch">批量删除</el-button>
    </div>

    <!--表格-->
    <el-table border highlight-current-row
              row-key="id"
              v-loading="option.loading" :data="option.tableData"
              @selection-change="selectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="角色ID" prop="id" :show-overflow-tooltip="true" width="220"></el-table-column>
      <el-table-column label="角色名称" prop="name" :show-overflow-tooltip="true" width="220"></el-table-column>
      <el-table-column label="备注信息" prop="remark" :show-overflow-tooltip="true" width="220"></el-table-column>
      <el-table-column label="创建人" prop="ca" width="100"></el-table-column>
      <el-table-column label="创建时间" prop="ct" width="170"></el-table-column>
      <el-table-column label="更新人" prop="ua" width="100"></el-table-column>
      <el-table-column label="更新时间" prop="ut" width="170"></el-table-column>
      <el-table-column label="排序" prop="sort" align="center" width="100"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="openEdit(scope.row)" v-hasPermi="['sys:menu:add']">
            编辑
          </el-button>
          <el-button link type="warning" icon="Menu" @click="openSelectMenu(scope.row)"
                     v-hasPermi="['sys:menu:edit']">
            菜单权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="fx_end">
      <el-pagination
          class="mgt8"
          small
          background
          :total="option.totalRow"
          :page-sizes="option.pageSizes"
          v-model:current-page="searchForm.pageNumber"
          v-model:page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="searchData"
          @current-change="searchData"
      />
    </div>

    <!--Dialog-->
    <el-dialog :title="option.dialogTitle" v-model="option.openDialog" width="680px" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>

      <el-form ref="formDataRef" size="default" :model="formData" :rules="formRules" label-width="100px">

        <el-form-item label="角色ID" prop="id" v-if="useUserStore().userInfo.root">
          <el-input :disabled="option.dialogType=='edit'" v-model="formData.id" placeholder="请输入"
                    style="width: 400px"/>
        </el-form-item>

        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" style="width: 400px"/>
        </el-form-item>

        <el-form-item label="当前状态" prop="isDisable">
          <el-radio-group v-model="formData.isDisable" style="width: 300px">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" controls-position="right" :min="0" style="width: 200px"/>
        </el-form-item>

        <el-form-item label="数据权限" prop="res">
          <el-input v-model="formData.res" maxlength="2000" placeholder="请输入拥有的数据权限（逗号分隔，禁止输入换行符）"
                    show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" style="width: 400px" type="textarea"
          />
        </el-form-item>

        <el-form-item label="排除权限" prop="resExclude">
          <el-input v-model="formData.resExclude" maxlength="2000"
                    placeholder="请输入排除的数据权限（逗号分隔，禁止输入换行符）"
                    show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" style="width: 400px" type="textarea"/>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
              v-model="formData.remark"
              maxlength="500"
              placeholder="请输入"
              show-word-limit
              :rows="2"
              style="width: 400px"
              type="textarea"
          />
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="()=>{option.openDialog=false}">取 消</el-button>
        <el-button v-if="option.dialogType==='add'" type="primary" @click="submitAdd">确 定</el-button>
        <el-button v-if="option.dialogType==='edit'" type="primary" @click="submitEdit">保 存</el-button>
      </template>

    </el-dialog>

    <el-dialog title="角色菜单" v-model="option.openMenuDialog" width="80%" :close-on-click-modal="false" draggable
               append-to-body destroy-on-close>

      <SelectMenu @call-back="selectMenuCallBack" :default-checked="option.defaultChecked"></SelectMenu>
      <template #footer>
        <el-button @click="()=>{option.openMenuDialog=false}">关 闭</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import {deleteRole, insertRole, pageRole, updateRole, updateRoleMenu} from "@/common/api/system";
import $modal from "@/common/utils/modal";
import SelectMenu from "@/module/common/selectMenu.vue";
import {copyNew} from "@/common/utils/kit";
import useUserStore from "@/common/store/userStore";
import {asDict} from "@/common/api/common";

const {enu_common_status} = asDict("enu_common_status");

const {proxy} = getCurrentInstance();

let optionKey = {
  loading: false,
  dialogType: "",
  dialogTitle: "",
  openDialog: false,
  openMenuDialog: false,
  tableData: [],
  selectIds: [],
  selectNames: [],
  pageSizes: [1, 10, 20, 50, 100],
  totalRow: 0,
  nowRoleId: 0,
  defaultChecked: [],
}
let formKey = {
  id: "",
  name: "",
  sort: 100,
  res: "",
  resExclude: "",
  //是否已禁用，0=正常，1=已禁用，默认为0
  isDisable: "0",
  remark: "",
}
let searchKey = {
  pageNumber: 1,
  pageSize: 10,
  name: "",
}

const formRules = ref({
  type: [{required: true, message: "不能为空", trigger: "change"}],
  sort: [{required: true, message: "不能为空", trigger: "blur"}],
  id: [{required: true, message: "不能为空", trigger: "blur"}],
  name: [{required: true, message: "不能为空", trigger: "blur"}],
});

const searchForm = ref(searchKey)
const formData = ref(formKey);
const option = ref(optionKey);

function resetForm() {
  formData.value = copyNew(formKey);
}

function resetSearch() {
  proxy.$refs["searchFormRef"].resetFields();
}

//页面加载完成回调
onMounted(() => {
  searchData()
})

function selectMenuCallBack(data) {
  ////console.log("selectMenuCallBack ", data.checkedNodes)

  let menuIds = []
  data.checkedNodes.filter(e => {
    menuIds.push(e.id)
  });
  ////console.log("option.value.nowRoleId ", option.value.nowRoleId)
  ////console.log("menuIds ", menuIds)
  updateRoleMenu({roleId: option.value.nowRoleId, menuIds: menuIds.join(",")}).then(res => {
    if (res.success) {
      option.value.nowRoleId = 0
      option.value.openMenuDialog = false
      $modal.success()
      searchData()
    }
  })
}

function selectionChange(rows) {
  option.value.selectIds = rows.map(item => item.id);
  option.value.selectNames = rows.map(item => item.name);
}

//搜索数据
function searchData() {
  option.value.loading = true;
  //console.log(searchForm.value)
  pageRole(searchForm.value).then(res => {
    let {totalRow, records, pageNumber, pageSize} = res.data;
    option.value.loading = false;
    option.value.totalRow = totalRow * 1
    option.value.tableData = records
    searchForm.value.pageNumber = pageNumber
    searchForm.value.pageSize = pageSize
  })
}

function openSelectMenu(row) {
  option.value.defaultChecked = row.menuIds;
  option.value.nowRoleId = row.id;
  option.value.openMenuDialog = true;
}

function openAdd() {
  resetForm()
  option.value.dialogTitle = "新增角色";
  option.value.openDialog = true;
  option.value.dialogType = "add";
}

function openEdit(row) {
  //console.log(row)
  option.value.dialogTitle = "编辑角色信息";
  option.value.openDialog = true;
  option.value.dialogType = "edit";
  formData.value = copyNew(row);
}

function submitAdd() {
  proxy.$refs["formDataRef"].validate(valid => {

    if (valid) {
      insertRole(formData.value).then(res => {
        if (res.success) {
          //console.log(res)
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })
    }

  });
}

function submitEdit() {
  proxy.$refs["formDataRef"].validate(valid => {

    if (valid) {
      updateRole(formData.value).then(res => {
        if (res.success) {
          //console.log(res)
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })
    }

  });
}

function deleteBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }

  //console.log(ids)
  let content = `正在删除名称为【 ${option.value.selectNames.join("、")}】 的数据项，是否确定删除？ `
  $modal.confirmWarning(content)
      .then(async () => {
        let res = await deleteRole({ids: option.value.selectIds.join(",")})
        if (res.success) {
          $modal.success();
          searchData()
        }
      }).catch(() => $modal.cancel());
}

</script>

<style scoped lang="less">

</style>